<template>
  <div class="app-container">
    <common-table
      :has-new="false"
      :has-modify="false"
      :has-delete="false"
      :colnames="colnames"
      :list-data="listData"
      :list-loading="listLoading"
      :is-multiple="isMultiSelect"
      :custom-buttons="customButtons"
      @fetchData="fetchData"
      @itemNew="itemNew"
      @itemEdit="itemEdit"
      @itemDelete="itemDelete"
      @onCustomButtonClick="onCustomButtonClick"
      @selectChange="onSelectChange"
    >
      <template v-slot:leftPannel>
        <el-button type="primary" size="mini" :disabled="selectedItems.length === 0" @click="onPriceModify">价格修改</el-button>
      </template>
      <template v-slot:filter>
        <!-- <el-button size="mini" type="default" @click="downloadTemplate()">下载模板</el-button>
          <el-button size="mini" type="primary" style="margin-right:80px;" @click="importData()">批量导入</el-button> -->
        <el-input v-model="listQuery.stationName" placeholder="请输入场站名称" clearable style="width: 220px;" size="mini" />
        <el-cascader
          v-model="filter.addrProvince"
          size="mini"
          :options="provinceOptions"
          placeholder="请选择地址"
          style="width: 220px;margin-left:15px;margin-right:15px;"
          clearable
          @change="addressChange"
        />
        <el-input v-model="listQuery.sectionName" placeholder="请输入场站分区" clearable class="etag" size="mini" />
        <el-select v-model="listQuery.priceType" placeholder="请选择价格类型" clearable class="esel" size="mini">
          <el-option label="一口价" value="1" />
          <el-option label="二段分时价" value="2" />
          <el-option label="三段分时价" value="3" />
          <el-option label="四段分时价" value="4" />
          <el-option label="五段分时价" value="5" />
          <el-option label="六段分时价" value="6" />
          <!-- <el-option label="非特斯拉分时价" value="10" /> -->
        </el-select>
        <el-select v-model="listQuery.templateType" placeholder="请选择模板类型" clearable class="esel" size="mini">
          <el-option label="标准" value="1" />
          <el-option label="自定义" value="2" />
        </el-select>
        <el-button type="primary" size="mini" class="ml5" @click="fetchData(listQuery)">查询</el-button>
        <el-button type="default" size="mini" class="ml5" @click="exportData(listQuery)">导出</el-button>
      </template>
    </common-table>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="40%"
      destroy-on-close
    >
      <price-edit
        :values="editValues"
        :readonly="!hasModify"
        @onCancel="dialogVisible = false"
        @onSubmit="onSubmit"
      />
    </el-dialog>

  </div>
</template>

<style scoped>
.etag {
  width: 220px;
  margin-right: 5px;
}
.esel {
  margin-right: 5px;
}
</style>

<script>
import { mapGetters } from 'vuex'
import CommonTable from '../commontable'
import PriceEdit from './edit'
import { delPrice, addPrice, putPrice, getSectionBasedPriceList, exportSectionBasedPriceList, putSectionBasedPrice } from '@/api/price'
import apiDefines from '../commontable/apidefines'
import { batchDel, mergeQuerrys } from '@/utils'
import { provinceAndCityData, CodeToText } from 'element-china-area-data'

export default {
  name: 'Price',
  components: { CommonTable, PriceEdit },
  data() {
    return {
      customButtons: [
        // { name: '价格修改', type: 'primary', data: { }}
        // { name: '查看引用', type: 'default', isMultiSelect: false, data: {}}
      ],
      colnames: [
        { displayName: '序号', colName: 'id', dataType: 'indexNo', colWidth: '64px' },
        { displayName: '名称', colName: 'stationName' },
        { displayName: '省市', dataType: 'combine', data: {
          cols: [{ name: 'addrProvince' }, { name: 'addrCity' }]
        }, sortable: false },
        { displayName: '场站分区', colName: 'sectionName' },
        { displayName: '价格类型', colName: 'typeName' },
        // { displayName: '价格模板', colName: 'templateName' },
        { displayName: '模板类型', colName: 'templateType', formater: (val, row) => {
          switch (row.templateType) {
            case 1: return '标准'
            case 2: return '自定义'
          }
        } },
        // { displayName: '模板图片', colName: 'fileUrl', dataType: 'image', colWidth: '120px' },
        { displayName: '显示价格', colName: 'usingTemplate.fileUrl', dataType: 'image', colWidth: '120px', sortable: false },
        { displayName: '设定价格', colName: 'fileUrl', dataType: 'image', colWidth: '120px', sortable: false },
        { displayName: '同步状态', colName: 'syncStatus', sortable: false, formater: (val, row) => {
          return row.usingTemplate && row.usingTemplate.otaId === row.otaId ? '是' : '否'
        } },
        { displayName: '一口价充电费', colName: 'chargePrice' },
        // { displayName: '电费', colName: 'electricity' },
        { displayName: '时段说明1', colName: 'desc1', hidden: true },
        { displayName: '时段1', colName: 'period1' },
        { displayName: '价格1', colName: 'price1', dataType: 'number' },
        { displayName: '时段说明2', colName: 'desc2', hidden: true },
        { displayName: '时段2', colName: 'period2' },
        { displayName: '价格2', colName: 'price2', dataType: 'number' },
        { displayName: '时段说明3', colName: 'desc3', hidden: true },
        { displayName: '时段3', colName: 'period3' },
        { displayName: '价格3', colName: 'price3', dataType: 'number' },
        { displayName: '超时充电费', colName: 'overtimePrice' }
        // {
        //   displayName: '操作', dataType: 'oprators', colWidth: '120px', data: {
        //     ops: [
        //       { name: '编辑', click: 'itemUpdate' },
        //       { name: '删除', click: 'itemDelete' }
        //     ]
        //   }
        // }
      ],
      editCols: {},
      editType: 'edit',
      editValues: {},
      listData: {},
      editRules: {},
      listLoading: false,
      isMultiSelect: true,
      dialogVisible: false,
      dialogTitle: '新建',
      stationName: '全部价格牌模板',
      listQuery: {},
      hasModify: false,
      provinceOptions: provinceAndCityData,
      filter: {
        addrProvince: []
      },
      selectedItems: []
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'name',
      'avatar',
      'roles'
    ])
  },
  created() {
    this.editCols = apiDefines.price.editCols
    this.editRules = apiDefines.price.editRules
  },
  mounted() {
    this.$nextTick(() => {
      if (this.$route.params.stationName) {
        this.stationName = this.$route.params.stationName + ' 车位'
      }
    })
  },
  methods: {
    fetchData(listQuery) {
      this.listQuery = listQuery
      console.log('fetchData', listQuery)
      this.listLoading = true
      const keyDefs = [
        { key: 'stationName', matchType: 'like' },
        { key: 'addrProvince', matchType: 'like' },
        { key: 'addrCity', matchType: 'like' },
        { key: 'sectionName', matchType: 'like' },
        { key: 'templateType', matchType: 'match' },
        { key: 'priceType', matchType: 'match' }
      ]
      getSectionBasedPriceList(mergeQuerrys(keyDefs, listQuery))
        .then(ret => {
          console.log('ret', ret)
          this.listData = ret.data
        }).finally(() => {
          this.listLoading = false
        })
    },
    itemNew() {
      console.log('price New')
      this.editType = 'add'
      this.dialogTitle = '新建一口价'
      this.editValues = { priceType: 1, templateType: 1, templateStyle: 4 }
      this.dialogVisible = true
      this.hasModify = true
    },
    itemEdit({ type, item, items }) {
      console.log('itemEdit')
      this.editType = 'edit'
      this.editValues = item
      this.dialogTitle = '修改'
      this.dialogVisible = true
      this.hasModify = false
    },
    itemDelete({ type, item, items }) {
      console.log('itemDelete')
      if (type === 'one') {
        delPrice({ priceId: item.id }).then(ret => {
          this.$message({
            type: 'success',
            message: '删除成功！'
          })
          this.fetchData(this.listQuery)
        })
      } else if (type === 'multi') {
        batchDel(delPrice, items, { idname: 'priceId', idvalue: 'id' }).then(ret => {
          this.$message({
            type: 'success',
            message: '删除成功！'
          })
          this.fetchData(this.listQuery)
        })
      }
    },
    onSubmit(formData) {
      console.log('onSubmitsss', formData)
      if (this.editType === 'add') {
        // 新建
        addPrice(formData).then((ret) => {
          console.log('添加新价格 ret:', ret)
          if (ret.data && ret.data.otaId) {
            // putSectionBasedPrice(this.selectedItems.map(v => { return { id: v.id } }), ret.data.otaId).then(ret => {
            console.log('价格修改 otaId:', ret.data.otaId, '数据：', this.selectedItems)
            putSectionBasedPrice(this.selectedItems, ret.data.otaId).then(ret => {
              this.$message({
                type: 'success',
                message: '修改成功！'
              })
              this.dialogVisible = false
              this.fetchData(this.listQuery)
            })
          } else {
            this.$message({
              type: 'error',
              message: '价格模板指定失败，没有获取到：otaId'
            })
          }
        })
      } else if (this.hasModify) {
        // 修改
        putPrice(formData).then((ret) => {
          console.log('edit ret', ret)
          this.dialogVisible = false
          this.$message({
            type: 'success',
            message: '修改成功！'
          })
          this.fetchData(this.listQuery)
        })
      } else {
        this.dialogVisible = false
      }
    },
    onCustomButtonClick({ target, data }) {
      console.log(target, data)
    },
    onSelectChange({ type, item, items }) {
      this.selectedItems = items
    },
    onPriceModify() {
      this.editType = 'add'
      this.dialogTitle = '价格修改'
      this.editValues = { priceType: 1, templateType: 1, templateStyle: 4 }
      this.dialogVisible = true
      this.hasModify = true
    },
    exportData(listQuery) {
      const keyDefs = [
        { key: 'stationName', matchType: 'like' },
        { key: 'addrProvince', matchType: 'like' },
        { key: 'addrCity', matchType: 'like' },
        { key: 'sectionName', matchType: 'like' },
        { key: 'templateType', matchType: 'match' },
        { key: 'priceType', matchType: 'match' }
      ]
      exportSectionBasedPriceList(mergeQuerrys(keyDefs, listQuery)).then(ret => {
        console.log(ret)
      })
    },
    addressChange(arr) {
      if (arr) {
        this.listQuery.addrProvince = CodeToText[arr[0]]
        this.listQuery.addrCity = CodeToText[arr[1]]
      } else {
        this.listQuery.addrProvince = ''
        this.listQuery.addrCity = ''
      }
    }
  }
}
</script>
